package com.tuniondata.netty.bean;

import com.tuniondata.netty.common.protocol.ApiProtocolException;
import com.tuniondata.netty.common.protocol.Protocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.Serializable;

/**
 * @author yuxinchao
 *
 * 公用请求响应封装
 */
public class RpcMessage implements Serializable {
    private static final Logger log = LoggerFactory.getLogger(RpcMessage.class);

    private String requestId;
    private Protocol protocol;

    public String getRequestId() {
        return requestId;
    }

    public void setRequestId(String requestId) {
        this.requestId = requestId;
    }

    public Protocol getProtocol() {
        return protocol;
    }

    public void setProtocol(Protocol protocol) {
        this.protocol = protocol;
    }

    public RpcMessage() {
    }

    public RpcMessage(byte[] data) throws ApiProtocolException {
        try {
            String content = new String(data);
            String protocolString = content.substring(0, content.length() - 36);
            this.protocol = new Protocol(protocolString.getBytes("GBK"));
            unpackRequestId(content.substring(content.length() - 36, content.length()));
            log.info("rpc protocol: {}, requestId: {}", this.protocol, this.requestId);
        } catch (IOException e) {
            throw new ApiProtocolException(e);
        }
    }

    public byte[] toByteArray() throws IOException {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(new String(this.protocol.toByteArray()))
                    .append(this.requestId);

        log.info("the rpc message pack string is {}", stringBuffer.toString());

        return stringBuffer.toString().getBytes("GBK");
    }

    private void unpackRequestId(String requestId) {
        this.requestId = requestId;
    }
}
